use std::{
    io::{Read, Write},
    net::TcpStream,
};

pub fn send(socket: &mut TcpStream, method: &str, data: &str) {
    let reply_auth = PayloadMessage {
        method: method.to_owned(),
        data: data.to_owned(),
    };
    socket.write_all(reply_auth.serialize().as_bytes()).unwrap();
}

pub fn recv(socket: &mut TcpStream, buf: &mut [u8]) -> PayloadMessage {
    let len = socket.read(buf).unwrap();
    PayloadMessage::deserialize(&buf[0..len]).unwrap()
}

#[derive(serde::Deserialize, serde::Serialize, Debug, Default, Clone)]
pub struct PayloadMessage {
    pub method: String,
    pub data: String,
}
impl PayloadMessage {
    pub fn new() -> Self {
        Self::default()
    }
    pub fn serialize(&self) -> String {
        serde_json::to_string(&self).unwrap()
    }
    pub fn deserialize(value: &[u8]) -> Result<Self, serde_json::Error> {
        serde_json::from_slice::<Self>(value)
    }
}
